Tensors

Tensors are similar to NumPy’s ndarrays, with the addition being that Tensors can also be used on a GPU to accelerate computing.


Construct a 5x3 matrix, uninitialized:

Construct a randomly initialized matrix:

Construct a matrix filled zeros and of dtype long:

Construct a tensor directly from data:

or create a tensor based on an existing tensor. These methods will reuse properties of the input tensor, e.g. dtype, unless new values are provided by user

Get its size:

Note:

Operations

Addition: syntax 1


Addition: syntax 2

Addition: providing an output tensor as argument

Addition: in-place

Note:

You can use standard NumPy-like indexing

Resizing: If you want to resize/reshape tensor, you can use torch.view:

Out:

If you have a one element tensor, use .item() to get the value as a Python number

Numpy Bridge

The Torch Tensor and NumPy array will share their underlying memory locations, and changing one will change the other.

Converting a Torch Tensor to a NumPy Array

Out:

Converting NumPy Array to Torch Tensor

out:


All the Tensors on the CPU except a CharTensor support converting to NumPy and back.

CUDA Tensors

Tensors can be moved onto any device using the .to method.


out:

examples

PyTorch: Custom nn Modules